"""
    Author:
    Date: 2018-10-30

    微信公众平台
"""

import time
import datetime
import requests

from django.conf import settings
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import redirect
from django.shortcuts import render
from django.urls import reverse

from entities import gm_mgr
from entities import pay_mgr
from entities import redis_mgr
from entities import user_mgr
from entities import vchat_api_mgr
from entities import version_mgr
from entities import unipay_mgr

from . import helpers
from . import models

from apps.gma import helpers as gma_helpers
from entities.consts import *
from utils import ajax
from utils import wx_util
from utils import wx_config
from utils import util
from utils.log import Log
from utils.wx_util import WechatApi


def about(request):
    """ 微信公众后台的关于页面 """
    wx_util.save_wx_code(request)

    # 如果是管理员则跳转到管理页面
    openid = helpers.get_request_openid(request)

    # GM点击这个页面直接跳转到管理页面
    user = gm_mgr.get_gm(openid)
    if (user is not None) and (user.profile is not None) and (user.profile.level > 1):
        gma_helpers.login(request, openid)
        return HttpResponseRedirect(reverse('gma:home'))

    context = helpers.build_context(request)
    return render(request, 'mp/about.html', context)


def agreement(request, app):
    """ 微信公众后台的关于页面 """
    app = app.strip().lower()
    context = helpers.build_context(request)
    return render(request, f'mp/apps/{app}/agreement.html', context)


def privacy(request, app):
    """ 微信公众后台的隐私页面 """
    app = app.strip().lower()
    context = helpers.build_context(request)
    return render(request, f'mp/apps/{app}/privacy.html', context)


def download_app(request, app):
    """ 下载APP """
    data = settings.APP_VERSION_DATA.get(app, None)
    if data is None:
        return helpers.show_warn_page(request, '无效的编号!')

    ios_channel = data['IOS']
    android_channel = data['ANDROID']
    context = helpers.build_context(request)
    context['config'] = version_mgr.get_version_config(ios_channel, android_channel)
    # return render(request, 'download_app.html', context)
    return render(request, 'download_app_v2.html', context)

def download_app_by_channel(request, app, channel):
    """ 根据channel下载app """
    data = settings.APP_VERSION_DATA.get(app, None)
    if data is None:
        return helpers.show_warn_page(request, '无效的编号!')

    ios_channel = data['IOS']
    android_channel = data['ANDROID']
    context = helpers.build_context(request)
    config = version_mgr.get_version_config(ios_channel, android_channel)
    config['android_download_url'] = f'https://res.yyzb.com/app/haibao_c{channel}.apk'
    context['config'] = config
    return render(request, 'download_app_v2.html', context)

# def pay(request):
#     """ 充值 """
#     wx_util.save_wx_code(request)
#
#     pay_url = 'https://m.yyzb.com/pay/'
#     jsapi_ticket = WechatApi.get_jsapi_ticket()
#     if jsapi_ticket is None:
#         return helpers.show_warn_page(request, '请求JSAPI票据失败!')
#
#     sign = wx_util.JsapiUtil(jsapi_ticket, pay_url).sign()
#     config = {
#         'appId': wx_config.APPID,
#         'timestamp': sign['timestamp'],
#         'nonceStr': sign['nonceStr'],
#         'signature': sign['signature'],
#     }
#
#     context = helpers.build_context(request)
#     context['config'] = config
#     return render(request, 'mp/pay.html', context)
#

def url_schemes(request, app_code, path):
    """ URL scheme """
    context = helpers.build_context(request)
    context['app_code'] = app_code
    context['path'] = path
    return render(request, 'mp/url_schemes.html', context)


def pay_v2(request):
    """ 微信和支付宝充值2.0版本，新界面 """
    wx_util.save_wx_code(request)
    context = helpers.build_context(request)
    return render(request, 'mp/pay/index.html', context)


def pay(request):
    """ 微信和支付宝充值 """
    wx_util.save_wx_code(request)
    code = request.GET.get('code', None)
    Log.info(f"Pay request: code={code}")

    # client_ip = util.get_request_real_ip(request)[0]
    # if client_ip == '114.88.215.19':
    #     context = helpers.build_context(request)
    #     return render(request, 'mp/pay/index.html', context)

    pay_url = 'https://m.yyzb.com/mp/pay/'
    jsapi_ticket = WechatApi.get_jsapi_ticket()
    if jsapi_ticket is None:
        return helpers.show_warn_page(request, '请求JSAPI票据失败!')

    sign = wx_util.JsapiUtil(jsapi_ticket, pay_url).sign()
    config = {
        'appId': wx_config.APPID,
        'timestamp': sign['timestamp'],
        'nonceStr': sign['nonceStr'],
        'signature': sign['signature'],
    }

    context = helpers.build_context(request)
    context['config'] = config
    return render(request, 'mp/pay/pay_with_wechat_mp.html', context)


def pay_with_ali(request):
    """ 支付宝充值 """
    wx_util.save_wx_code(request)

    context = helpers.build_context(request)
    return render(request, 'mp/pay/pay_with_ali.html', context)


def pay_with_hsq(request):
    """ 慧收钱公众号充值 """
    wx_util.save_wx_code(request)
    return redirect('https://m.yyzb.com/static/mp/index.html')


def withdraw(request):
    """ 提现页面 """
    wx_util.save_wx_code(request)
    context = helpers.build_context(request)
    # return render(request, 'mp/coming_soon.html', context)
    return render(request, 'mp/withdraw/index.html', context)


def api_get_prepay_info(request):
    """ 获取预支付信息 """
    uid = int(request.POST['uid'].strip())
    rmb = int(request.POST['rmb'].strip())
    code = request.POST.get('code', None)
    Log.info(f"api_get_prepay_info: uid={uid}, rmb={rmb}, code={code}")

    if code:
        wx_util.save_wx_code(request, code)

    # 查看是否获取用户信息成功
    openid = helpers.get_request_openid(request)
    if openid is None:
        return ajax.error_response('获取用户信息失败！')

    # 检测用户id是否合法
    if not user_mgr.is_valid_uid(uid):
        return ajax.error_response('无效的用户ID！')

    # 检测请求ip是否合法
    client_ip = util.get_request_real_ip(request)[0]
    key = redis_mgr.KEY_USER_PAY_IP % uid
    cached_pay_ip = redis_mgr.get_cached_string(key)
    if client_ip != cached_pay_ip:
        return ajax.error_response(f'充值异常! 您正在充值￥{rmb}给账号{uid}, 请确认这是否是您自己的账号。')

    # 创建订单
    params = pay_mgr.create_prepay_record(uid, rmb, openid)
    if params is None:
        return ajax.error_response('支付失败！')
    Log.info(f'api_get_prepay_info: params={params}')

    return ajax.success_response(params)


# def api_get_unipay_mp_prepay_info(request, uid, rmb):
#     """ 获取银联公众号预支付信息 """
#     # uid = int(request.POST['uid'].strip())
#     # rmb = int(request.POST['rmb'].strip())
#     uid = int(uid)
#     rmb = int(rmb)
#
#     # 创建 out_trade_no
#     out_trade_no = unipay_mgr.create_order_no(uid, rmb, settings.UNIPAY_MSG_SRC_ID)
#     if out_trade_no is None:
#         Log.error('Fetch out_trade_no from api-server failed!')
#         return helpers.show_warn_page(request, '创建订单失败!')
#     Log.info(f'Fetch out_trade_no for unipay mp from api-server: {out_trade_no}!')
#
#     # 处理测试账号的充值金额
#     amount = 100*rmb
#     if uid in settings.TEST_UIDS_FOR_PAY:
#         amount = 1
#
#     url = settings.UNIPAY_URL
#     params = {
#         # 消息来源
#         'msgSrc': settings.UNIPAY_MSG_SRC,
#         # 消息类型(非必传: WXPay.jsPay :微信公众号支付, trade.jsPay :支付宝, acp.jsPay :银联云闪付)
#         # 'msgType': 'WXPay.jsPay',
#         # 报文请求时间，格式yyyy-MM-dd HH:mm:ss
#         'requestTimestamp': util.now(),
#         # 商户订单号, 长度6到32位
#         'merOrderId': out_trade_no,
#         # 商户号
#         'mid': settings.UNIPAY_MID,
#         # 终端号
#         'tid': settings.UNIPAY_TID,
#         # 支付总金额，单位分
#         'totalAmount': amount,
#         # 支付结果通知地址
#         'notifyUrl': 'https://test.api.yyzb.com/notify/unipayMp/',
#         # 网页跳转地址
#         # 'returnUrl': '',
#     }
#     sign = unipay_mgr.build_sign(params, settings.UNIPAY_SECRET)
#     params['sign'] = sign
#     Log.info(f'GET unipay: url={url}, params={params}')
#
#     response = requests.get(url, params=params)
#     Log.info(f'GET unipay result: {response.text}')
#     return HttpResponse(response)
#     # return HttpResponseRedirect(response)


def api_user_info(request):
    """ 查询用户基本信息 """
    uid = int(request.POST['uid'].strip())
    Log.info(f"Find user info for {uid}")

    user = user_mgr.get_user_detail(uid)
    if user is None:
        Log.info(f"Find user info for {uid} failed!")
        return ajax.error_response('')
        # user = user_mgr.get_user_detail_by_mobile(uid)
        # if user is None:
        #     Log.info(f"Find user info for {uid} failed!")
        #     return ajax.error_response('')

    # 判断用户是否实名认证过
    certified = 0

    data = {
        'avatar': user['avatar'],
        'nickname': user['nickname'],
        'certified': certified,
    }
    return ajax.success_response(data, 'SUCCESS')


# def api_get_hsq_mp_prepay_info(request):
#     """ 获取慧收钱的公众号预支付信息 """
#     # 提取参数
#     uid = int(request.POST['uid'].strip())
#     amount = int(request.POST['amount'].strip())
#
#     appid = settings.WX_MP_APPID
#     openid = helpers.get_request_openid(request)
#     client_ip = util.get_request_real_ip(request)[0]
#     result = vchat_api_mgr.prepay_with_hsq_mp(uid, amount, appid, openid, client_ip)
#
#     # 请求接口
#     Log.info(f'Request api result: {result}')
#     if result is None:
#         return ajax.error_response('支付失败！')
#
#     return ajax.success_response(result)


if __name__ == '__main__':
    print('ok')
